/// 发布视频集合页面
/// 
/// 用于创建和编辑视频集合
/// 
/// @author Matrix
/// @version 1.0.0
/// @since 2025-11-26

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import '../../models/collection_model.dart';
import '../../services/collection_service.dart';
import '../../utils/logger.dart';
import '../../utils/compress_utils.dart';
import '../../utils/cached_image_widget.dart';

/// 发布集合页面
class PublishCollectionPage extends StatefulWidget {
  /// 编辑模式时传入的集合（null表示创建新集合）
  final CollectionModel? collection;

  const PublishCollectionPage({
    super.key,
    this.collection,
  });

  @override
  State<PublishCollectionPage> createState() => _PublishCollectionPageState();
}

class _PublishCollectionPageState extends State<PublishCollectionPage> {
  /// 集合服务
  final CollectionService _collectionService = CollectionService();
  
  /// 图片选择器
  final ImagePicker _imagePicker = ImagePicker();
  
  /// 表单Key
  final _formKey = GlobalKey<FormState>();
  
  /// 标题控制器
  final _titleController = TextEditingController();
  
  /// 描述控制器
  final _descriptionController = TextEditingController();
  
  /// 封面图URL
  String? _coverUrl;
  
  /// 本地封面图文件
  File? _coverFile;
  
  /// 访问类型
  String _accessType = 'public';
  
  /// 是否立即发布
  bool _publishNow = false;
  
  /// 是否正在提交
  bool _isSubmitting = false;
  
  /// 是否是编辑模式
  bool get _isEditMode => widget.collection != null;

  /// 预设标签列表
  List<String> _presetTags = [];
  
  /// 已选择的标签
  List<String> _selectedTags = [];
  
  /// 是否正在加载标签
  bool _isLoadingTags = false;

  @override
  void initState() {
    super.initState();
    _loadPresetTags();
    _initFormData();
  }

  @override
  void dispose() {
    _titleController.dispose();
    _descriptionController.dispose();
    super.dispose();
  }

  /// 加载预设标签
  Future<void> _loadPresetTags() async {
    setState(() => _isLoadingTags = true);
    try {
      _presetTags = await _collectionService.getPresetTags();
      Logger.d('PUBLISH_COLLECTION', '加载预设标签成功: ${_presetTags.length}个');
    } catch (e) {
      Logger.e('PUBLISH_COLLECTION', '加载预设标签失败: $e');
    } finally {
      setState(() => _isLoadingTags = false);
    }
  }

  /// 初始化表单数据（编辑模式）
  void _initFormData() {
    if (_isEditMode) {
      final collection = widget.collection!;
      _titleController.text = collection.title;
      _descriptionController.text = collection.description ?? '';
      _selectedTags = List.from(collection.tags);
      _coverUrl = collection.coverUrl;
      _accessType = collection.accessType;
      _publishNow = collection.status == 'published';
    }
  }

  /// 选择封面图
  Future<void> _pickCoverImage() async {
    try {
      final pickedFile = await _imagePicker.pickImage(
        source: ImageSource.gallery,
        maxWidth: 1920,
        maxHeight: 1080,
      );
      
      if (pickedFile != null) {
        setState(() {
          _coverFile = File(pickedFile.path);
          _coverUrl = null; // 清除远程URL
        });
        Logger.d('PUBLISH_COLLECTION', '选择封面图: ${pickedFile.path}');
      }
    } catch (e) {
      Logger.e('PUBLISH_COLLECTION', '选择封面图失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('选择图片失败: $e')),
      );
    }
  }

  /// 上传封面图
  Future<String?> _uploadCoverImage() async {
    if (_coverFile == null) return _coverUrl;
    
    try {
      // 压缩图片
      final compressedFile = await CompressUtils.compressCoverImage(_coverFile!);
      final fileToUpload = compressedFile ?? _coverFile!;
      
      // 上传
      final url = await _collectionService.uploadCoverImage(fileToUpload);
      Logger.d('PUBLISH_COLLECTION', '封面上传成功: $url');
      return url;
    } catch (e) {
      Logger.e('PUBLISH_COLLECTION', '上传封面失败: $e');
      throw Exception('上传封面失败: $e');
    }
  }

  /// 提交表单
  Future<void> _submit() async {
    if (!_formKey.currentState!.validate()) return;
    
    // 检查封面
    if (_coverFile == null && _coverUrl == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请选择封面图')),
      );
      return;
    }

    setState(() => _isSubmitting = true);

    try {
      // 上传封面图
      final coverUrl = await _uploadCoverImage();
      
      // 确定状态
      final status = _publishNow ? 'published' : 'draft';
      
      if (_isEditMode) {
        // 更新集合
        await _collectionService.updateCollection(
          id: widget.collection!.id,
          title: _titleController.text.trim(),
          description: _descriptionController.text.trim(),
          coverUrl: coverUrl,
          tags: _selectedTags,
          accessType: _accessType,
          status: status,
        );
        
        Logger.d('PUBLISH_COLLECTION', '更新集合成功');
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('更新成功')),
        );
      } else {
        // 创建集合
        final collectionId = await _collectionService.createCollection(
          title: _titleController.text.trim(),
          description: _descriptionController.text.trim(),
          coverUrl: coverUrl,
          tags: _selectedTags,
          accessType: _accessType,
          status: status,
        );
        
        Logger.d('PUBLISH_COLLECTION', '创建集合成功，ID: $collectionId');
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(_publishNow ? '发布成功' : '保存为草稿成功')),
        );
      }
      
      Navigator.pop(context, true);
    } catch (e) {
      Logger.e('PUBLISH_COLLECTION', '提交失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('操作失败: $e')),
      );
    } finally {
      setState(() => _isSubmitting = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_isEditMode ? '编辑集合' : '新建视频集合'),
        actions: [
          TextButton(
            onPressed: _isSubmitting ? null : _submit,
            child: _isSubmitting
                ? const SizedBox(
                    width: 20,
                    height: 20,
                    child: CircularProgressIndicator(strokeWidth: 2),
                  )
                : Text(
                    _isEditMode ? '保存' : (_publishNow ? '发布' : '保存草稿'),
                    style: const TextStyle(color: Colors.white),
                  ),
          ),
        ],
      ),
      body: Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.all(16),
          children: [
            // 封面选择
            _buildCoverSelector(),
            const SizedBox(height: 24),
            
            // 标题
            TextFormField(
              controller: _titleController,
              decoration: const InputDecoration(
                labelText: '集合标题 *',
                hintText: '请输入集合标题',
                border: OutlineInputBorder(),
              ),
              maxLength: 50,
              validator: (value) {
                if (value == null || value.trim().isEmpty) {
                  return '请输入集合标题';
                }
                if (value.trim().length < 2) {
                  return '标题至少2个字符';
                }
                return null;
              },
            ),
            const SizedBox(height: 16),
            
            // 描述
            TextFormField(
              controller: _descriptionController,
              decoration: const InputDecoration(
                labelText: '集合描述',
                hintText: '请输入集合描述（可选）',
                border: OutlineInputBorder(),
              ),
              maxLines: 4,
              maxLength: 500,
            ),
            const SizedBox(height: 16),
            
            // 标签选择
            _buildTagSelector(),
            const SizedBox(height: 24),
            
            // 访问权限
            _buildAccessTypeSelector(),
            const SizedBox(height: 24),
            
            // 发布选项
            _buildPublishOption(),
          ],
        ),
      ),
    );
  }

  /// 构建封面选择器
  Widget _buildCoverSelector() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '集合封面 *',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w500,
          ),
        ),
        const SizedBox(height: 8),
        GestureDetector(
          onTap: _pickCoverImage,
          child: Container(
            width: double.infinity,
            height: 180,
            decoration: BoxDecoration(
              color: Colors.grey[100],
              borderRadius: BorderRadius.circular(8),
              border: Border.all(color: Colors.grey[300]!),
            ),
            child: _coverFile != null
                ? ClipRRect(
                    borderRadius: BorderRadius.circular(8),
                    child: Stack(
                      fit: StackFit.expand,
                      children: [
                        Image.file(
                          _coverFile!,
                          fit: BoxFit.cover,
                        ),
                        Positioned(
                          right: 8,
                          top: 8,
                          child: Container(
                            padding: const EdgeInsets.all(4),
                            decoration: const BoxDecoration(
                              color: Colors.black54,
                              shape: BoxShape.circle,
                            ),
                            child: const Icon(
                              Icons.edit,
                              color: Colors.white,
                              size: 20,
                            ),
                          ),
                        ),
                      ],
                    ),
                  )
                : (_coverUrl != null && _coverUrl!.isNotEmpty
                    ? ClipRRect(
                        borderRadius: BorderRadius.circular(8),
                        child: Stack(
                          fit: StackFit.expand,
                          children: [
                            CachedImageWidget(
                              imageUrl: _coverUrl,
                              fit: BoxFit.cover,
                              imageType: '集合封面',
                            ),
                            Positioned(
                              right: 8,
                              top: 8,
                              child: Container(
                                padding: const EdgeInsets.all(4),
                                decoration: const BoxDecoration(
                                  color: Colors.black54,
                                  shape: BoxShape.circle,
                                ),
                                child: const Icon(
                                  Icons.edit,
                                  color: Colors.white,
                                  size: 20,
                                ),
                              ),
                            ),
                          ],
                        ),
                      )
                    : Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(
                            Icons.add_photo_alternate,
                            size: 48,
                            color: Colors.grey[400],
                          ),
                          const SizedBox(height: 8),
                          Text(
                            '点击选择封面图',
                            style: TextStyle(
                              color: Colors.grey[600],
                              fontSize: 14,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            '建议尺寸: 16:9',
                            style: TextStyle(
                              color: Colors.grey[400],
                              fontSize: 12,
                            ),
                          ),
                        ],
                      )),
          ),
        ),
      ],
    );
  }

  /// 构建标签选择器
  Widget _buildTagSelector() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            const Text(
              '标签',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
              ),
            ),
            const SizedBox(width: 8),
            Text(
              '(已选 ${_selectedTags.length} 个)',
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey[600],
              ),
            ),
          ],
        ),
        const SizedBox(height: 12),
        
        // 已选择的标签
        if (_selectedTags.isNotEmpty) ...[
          Wrap(
            spacing: 8,
            runSpacing: 8,
            children: _selectedTags.map((tag) {
              return Chip(
                label: Text(tag),
                deleteIcon: const Icon(Icons.close, size: 18),
                onDeleted: () {
                  setState(() {
                    _selectedTags.remove(tag);
                  });
                },
                backgroundColor: Theme.of(context).primaryColor.withOpacity(0.1),
                labelStyle: TextStyle(
                  color: Theme.of(context).primaryColor,
                ),
              );
            }).toList(),
          ),
          const SizedBox(height: 12),
        ],
        
        // 预设标签选择
        if (_isLoadingTags)
          const Center(
            child: Padding(
              padding: EdgeInsets.all(16),
              child: CircularProgressIndicator(),
            ),
          )
        else
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: Colors.grey[50],
              borderRadius: BorderRadius.circular(8),
              border: Border.all(color: Colors.grey[200]!),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '点击选择标签',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                  ),
                ),
                const SizedBox(height: 8),
                Wrap(
                  spacing: 8,
                  runSpacing: 8,
                  children: _presetTags.map((tag) {
                    final isSelected = _selectedTags.contains(tag);
                    return GestureDetector(
                      onTap: () {
                        setState(() {
                          if (isSelected) {
                            _selectedTags.remove(tag);
                          } else {
                            if (_selectedTags.length < 5) {
                              _selectedTags.add(tag);
                            } else {
                              ScaffoldMessenger.of(context).showSnackBar(
                                const SnackBar(content: Text('最多选择5个标签')),
                              );
                            }
                          }
                        });
                      },
                      child: Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 12,
                          vertical: 6,
                        ),
                        decoration: BoxDecoration(
                          color: isSelected
                              ? Theme.of(context).primaryColor
                              : Colors.white,
                          borderRadius: BorderRadius.circular(16),
                          border: Border.all(
                            color: isSelected
                                ? Theme.of(context).primaryColor
                                : Colors.grey[300]!,
                          ),
                        ),
                        child: Text(
                          tag,
                          style: TextStyle(
                            fontSize: 13,
                            color: isSelected ? Colors.white : Colors.grey[700],
                          ),
                        ),
                      ),
                    );
                  }).toList(),
                ),
              ],
            ),
          ),
      ],
    );
  }

  /// 构建访问权限选择器
  Widget _buildAccessTypeSelector() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '访问权限',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w500,
          ),
        ),
        const SizedBox(height: 8),
        Row(
          children: [
            Expanded(
              child: _buildAccessTypeOption(
                'public',
                '公开',
                '所有人可见',
                Icons.public,
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: _buildAccessTypeOption(
                'whitelist',
                '白名单',
                '仅指定用户可见',
                Icons.lock,
              ),
            ),
          ],
        ),
        if (_accessType == 'whitelist') ...[
          const SizedBox(height: 12),
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: Colors.blue[50],
              borderRadius: BorderRadius.circular(8),
              border: Border.all(color: Colors.blue[200]!),
            ),
            child: Row(
              children: [
                Icon(Icons.info_outline, color: Colors.blue[700], size: 20),
                const SizedBox(width: 8),
                Expanded(
                  child: Text(
                    '创建后可在集合详情页管理白名单用户',
                    style: TextStyle(
                      color: Colors.blue[700],
                      fontSize: 13,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ],
    );
  }

  /// 构建访问类型选项
  Widget _buildAccessTypeOption(
    String value,
    String title,
    String subtitle,
    IconData icon,
  ) {
    final isSelected = _accessType == value;
    return GestureDetector(
      onTap: () => setState(() => _accessType = value),
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: isSelected
              ? Theme.of(context).primaryColor.withOpacity(0.1)
              : Colors.grey[100],
          borderRadius: BorderRadius.circular(8),
          border: Border.all(
            color: isSelected
                ? Theme.of(context).primaryColor
                : Colors.grey[300]!,
            width: isSelected ? 2 : 1,
          ),
        ),
        child: Column(
          children: [
            Icon(
              icon,
              size: 28,
              color: isSelected
                  ? Theme.of(context).primaryColor
                  : Colors.grey[600],
            ),
            const SizedBox(height: 8),
            Text(
              title,
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w600,
                color: isSelected
                    ? Theme.of(context).primaryColor
                    : Colors.grey[800],
              ),
            ),
            const SizedBox(height: 4),
            Text(
              subtitle,
              style: TextStyle(
                fontSize: 11,
                color: Colors.grey[600],
              ),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }

  /// 构建发布选项
  Widget _buildPublishOption() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: Row(
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  '立即发布',
                  style: TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  _publishNow ? '集合将对外可见' : '保存为草稿，稍后发布',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          ),
          Switch(
            value: _publishNow,
            onChanged: (value) => setState(() => _publishNow = value),
          ),
        ],
      ),
    );
  }
}
